from __future__ import annotations

"""Thin wrapper around memU to keep this app dependency-light.

We only need MemoryFileManager for file IO. This module attempts to import
memU from a local checkout if it's not installed. If import still fails,
we fall back to a minimal file manager with compatible methods we use.
"""

import os
import sys
from dataclasses import dataclass
from pathlib import Path
from typing import Dict, List, Literal


def _try_import_memu():
    try:
        import memu  # type: ignore
        return memu
    except Exception:
        # Try local checkout path from env or default
        local = os.getenv("MEMU_PATH") or "/home/linden/claude/git/memU"
        if Path(local).exists() and str(local) not in sys.path:
            sys.path.insert(0, str(local))
        try:
            import memu  # type: ignore
            return memu
        except Exception:
            return None


MEMU = _try_import_memu()


if MEMU is not None:
    # Use real implementation
    MemoryFileManager = MEMU.memory.MemoryFileManager  # type: ignore[attr-defined]
else:
    # Minimal fallback used only if memU is unavailable.
    class MemoryFileManager:  # type: ignore[no-redef]
        DEFAULT_EXTENSION = ".md"

        def __init__(self, memory_dir: str, agent_id: str | None = None, user_id: str | None = None):
            self.memory_dir = Path(memory_dir)
            self.memory_dir.mkdir(parents=True, exist_ok=True)
            self.embeddings_dir = self.memory_dir / "embeddings"
            self.embeddings_dir.mkdir(parents=True, exist_ok=True)
            self.agent_id = agent_id or "me"
            self.user_id = user_id or "me"
            # Basic mapping similar to memU defaults
            self.memory_types: Dict[str, Dict[str, str]] = {
                "basic": {"profile": "profile.md", "event": "event.md", "activity": "activity.md"},
                "cluster": {},
            }

        def _get_memory_file_path(self, agent_id: str, user_id: str, category: str) -> Path:
            mapping = self.memory_types["basic"].get(category, f"{category}{self.DEFAULT_EXTENSION}")
            return self.memory_dir / agent_id / user_id / mapping

        def read_memory_file(self, category: str) -> str:
            p = self._get_memory_file_path(self.agent_id, self.user_id, category)
            return p.read_text(encoding="utf-8") if p.exists() else ""

        def write_memory_file(self, category: str, content: str) -> bool:
            p = self._get_memory_file_path(self.agent_id, self.user_id, category)
            p.parent.mkdir(parents=True, exist_ok=True)
            p.write_text(content, encoding="utf-8")
            return True

        def append_memory_file(self, category: str, content: str) -> bool:
            old = self.read_memory_file(category)
            return self.write_memory_file(category, (old + "\n" if old else "") + content)

        def list_memory_files(self, category_group: Literal["basic", "cluster", "all"] = "basic") -> List[str]:
            if category_group == "basic":
                return sorted(list(self.memory_types["basic"].keys()))
            if category_group == "cluster":
                return []
            return sorted(list(self.memory_types["basic"].keys()))

